#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/10/14  13:33
# @Author: 余浪人
# @email: yulangren520@gmail.com
import requests, json
from fake_useragent import UserAgent
from flask import request, jsonify, current_app
from flask_login import login_required
from apps.control import sys_bp
from apps.lib.public import redis_
from apps.lib.token import Verify_authorization
from apps.lib.verifyCode import createMain


# 短网址生成
@sys_bp.route('/createUrl', endpoint='createUrl', methods=['POST'])
@login_required
@Verify_authorization
def createUrl():
    '''
        短网址生成
        :param url: 原网址
        :param cls: 短网址类型    0 > dwz.lc   1> ons.red   2> soso.bz   3>maa.la   4> ecx.cx   5> did.red
        :return: 短网址
        '''
    try:
        url = request.form.get('url', '')
        cls = int(request.form.get('cls', 0))
        userAgent = UserAgent()
        if not isinstance(cls, int): return jsonify({'status': 1, 'msg': '生成格式错误!'})
        if cls == 0:
            ci = 'dwz.lc'
        elif cls == 1:
            ci = 'ons.red'
        elif cls == 2:
            ci = 'soso.bz'
        elif cls == 3:
            ci = 'maa.la'
        elif cls == 4:
            ci = 'ecx.cx'
        else:
            ci = 'did.red'
        get_url = 'https://www.xyixy.com/shorten'
        paramData = {
            'url': '',
            'urls': url,
            'domain': f'https://{ci}',
            'multiple': '1',
            'ocation[]': '海南'
        }
        headers = {'User-Agent': userAgent.random}
        response = requests.post(get_url, data=paramData, headers=headers)
        if response.status_code == 200 and response.json().get('error') == 0:
            webSite = response.json()['short']
            if webSite:
                return jsonify({'status': 0, 'msg': '生成成功!', 'url': webSite})
        return jsonify({'status': 1, 'msg': '生成失败!'})
    except:
        return jsonify({'status': 1, 'msg': '生成异常!'})


# 获取验证码
@sys_bp.route('/verifyCode_<int:width>_<int:height>', endpoint='createVerify', methods=['GET'])
def createVerify(width: int, height: int):
    code, img = createMain(width, height)
    r_0 = redis_(db=0)
    r_0.set(f'tl_{request.remote_addr}', json.dumps(code), current_app.config['VERIFY_CODE_TIME'] * 60)
    return jsonify({'status': 0, 'imgCode': img})
